package com.authine.cloudpivot.web.api.service.impl;

import com.authine.cloudpivot.web.api.dao.ProjectTaskIssueMapper;
import com.authine.cloudpivot.web.api.dao.UserMapper;
import com.authine.cloudpivot.web.api.domain.dto.LeJuanDataDTO;
import com.authine.cloudpivot.web.api.service.GetLeJuanDataService;
import com.authine.cloudpivot.web.api.util.HttpRequestUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuN
 * @description
 * @date 2021/3/3
 */
@Slf4j
@Service
@Transactional
public class GetLeJuanDataServiceImpl implements GetLeJuanDataService {


   @Autowired
   private  ProjectTaskIssueMapper projectTaskIssueMapper;

   @Autowired
   private FescoadQueryServiceImpl fescoadQueryService;

    @Autowired
    private UserMapper userMapper;


   /**
    * @Description : 获取乐卷数据
    * @param ：
    * @author : Liun
    * @date : 2021/3/3
    */
   @Override
   public List<LeJuanDataDTO> getDataFromLejuan(String url, Map<String, String> parameters){

       String res= HttpRequestUtil.sendGet(url,parameters);
       JSONObject jsonStr = JSONObject.fromObject(res);

       boolean Status = jsonStr.getBoolean("Status");
       String data = jsonStr.getString("Data");

       List<LeJuanDataDTO> dataList = new ArrayList<LeJuanDataDTO>();
       if(Status){
           Gson gson = new Gson();
           dataList = gson.fromJson(data, new TypeToken<List<LeJuanDataDTO>>(){}.getType());
       }
        return dataList;
    }


   /**
    * @Description :删除已存在的项目任务下发数据
    * @param ：
    * @author : Liun
    * @date : 2021/3/5
    */
   @Override
   public Integer deleteProjectTaskIssueExist(String project_name,String QC_task_name){

       Integer count = projectTaskIssueMapper.deleteProjectTaskIssueExist(project_name,QC_task_name);
       return count;
   }


   /**
    * @Description : 获取项目QC任务名称
    * @param ：
    * @author : Liun
    * @date : 2021/3/5
    */
   @Override
   public  List<Map<String,String>> getProjectNames(){
       Map<String,String> dateMap=getTimes(-3);
       String beginTime=dateMap.get("beginTime");
       String endTime=dateMap.get("endTime");
       List<Map<String,String>> list = projectTaskIssueMapper.getProjectQcNames(beginTime,endTime);

      return list;

   }



   public Map getTimes(Integer days){
       Map<String ,String> dateMap=new HashMap<>();
       //当前日期
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       Calendar c = Calendar.getInstance();
       c.setTime(new Date());
       Date end = c.getTime();
       String endTime= format.format(end);

       //前三天
       c.add(Calendar.DATE, days);
       Date begin = c.getTime();
       String beginTime= format.format(begin);

       dateMap.put("beginTime",beginTime);
       dateMap.put("endTime",endTime);

       return dateMap;
   }



   @Override
    public void updateEndProportion(String tableName){
        Map<String,String> dateMap=getTimes(-120);
        String beginTime=dateMap.get("beginTime");
        String endTime=dateMap.get("endTime");
        List<Map>  taskSendList=projectTaskIssueMapper.getTaskSendList(tableName,beginTime,endTime);

        List<Map> updateTaskSendList=new ArrayList<>();
       BigDecimal demo0=new BigDecimal(0);
       BigDecimal demo=new BigDecimal(100);
        for(Map map:taskSendList){
            BigDecimal task_sum=(BigDecimal) map.get("task_sum");
            BigDecimal end_sum=(BigDecimal) map.get("end_sum");
            if(task_sum.compareTo(demo0)>0){
                BigDecimal end_proportion=end_sum.divide(task_sum,20,BigDecimal.ROUND_HALF_UP).multiply(demo);
                Map udapteMap=new HashMap();
                udapteMap.put("end_proportion",end_proportion);
                udapteMap.put("id",map.get("id"));
                updateTaskSendList.add(udapteMap);
            }

        }

       if(updateTaskSendList.size()>0){
           for(Map map:updateTaskSendList){
               projectTaskIssueMapper.updateTaskSendList(tableName,map);
           }
       }


    }





    /**
     * @Description : 修改项目任务新增中走访完成率和审核完成率
     * @param ：
     * @author : Liun
     * @date : 2021/3/17
     */
    @Override
    public void updateVisitAndAuditEndProbability(){
        Map<String,String> dateMap=getTimes(-120);
        String beginTime=dateMap.get("beginTime");
        String endTime=dateMap.get("endTime");

        List<Map>  QCTaskList=projectTaskIssueMapper.getQCTaskList(beginTime,endTime);

        List<Map> updateQCTaskList=new ArrayList<>();

        BigDecimal demo=new BigDecimal(100);
        BigDecimal demo0=new BigDecimal(0);
        for(Map map:QCTaskList){
            Integer changeStoreNum=(Integer) map.get("changeStoreNum");

            BigDecimal store_count=(BigDecimal) map.get("store_count");
            BigDecimal changeTotalNum=(BigDecimal) map.get("changeTotalNum");

            BigDecimal uploading_questionnaire_nmb=(BigDecimal) map.get("uploading_questionnaire_nmb");
            BigDecimal visit_end_probability=(BigDecimal) map.get("visit_end_probability");

            BigDecimal end_questionnaire_nmb=(BigDecimal) map.get("end_questionnaire_nmb");
            BigDecimal audit_end_probability=(BigDecimal) map.get("audit_end_probability");

            if(changeStoreNum==1&changeTotalNum.compareTo(demo0)>0){
                visit_end_probability=uploading_questionnaire_nmb.divide(changeTotalNum,20,BigDecimal.ROUND_HALF_UP).multiply(demo);
                audit_end_probability=end_questionnaire_nmb.divide(changeTotalNum,20,BigDecimal.ROUND_HALF_UP).multiply(demo);
            }else  if(changeStoreNum==0&store_count.compareTo(demo0)>0){
                visit_end_probability=uploading_questionnaire_nmb.divide(store_count,20,BigDecimal.ROUND_HALF_UP).multiply(demo);
                audit_end_probability=end_questionnaire_nmb.divide(store_count,20,BigDecimal.ROUND_HALF_UP).multiply(demo);
            }

            Map udapteMap=new HashMap();
            udapteMap.put("visit_end_probability",visit_end_probability);
            udapteMap.put("audit_end_probability",audit_end_probability);
            udapteMap.put("realId",map.get("id"));
            updateQCTaskList.add(udapteMap);
        }
        if(updateQCTaskList.size()>0){
            for(Map map:updateQCTaskList){
                projectTaskIssueMapper.updateQCTaskList(map);
            }
        }
    }

    @Override
    public Integer getQCTaskStoreCount(String projectName, String qCTaskName ) {
        return projectTaskIssueMapper.getQCTaskStoreCount(projectName,qCTaskName);
    }
    @Override
    public Map<String,Integer>  getTaskStatistics(String projectName, String qCTaskName ) {
        return projectTaskIssueMapper.getTaskStatistics(projectName,qCTaskName);
    }


    /**
     * @Description : QC项目任务下发，自建任务下发人员发送待办通知
     * @param ：
     * @author : Liun
     * @date : 2021/3/23
     */
    @Override
    public void  sendMessageToQCProjectTask(){
        String url = "form/detail?schemaCode=ProjectTaskIssue&sheetCode=ProjectTaskIssue";
        List<Map> taskList=projectTaskIssueMapper.getQCProjectTaskIssueList();
        String state;
        String project_name;
        String QC_task_name;
        String objectNumber;
        String QC_name;
        String content;
        String  QC_nameId;
        JSONObject jsonStr;
        if(taskList.size()>0){
            for(Map map:taskList){
                state=  map.get("state").toString();
                project_name=map.get("project_name").toString();
                QC_task_name=map.get("QC_task_name").toString();
                objectNumber=map.get("objectNumber").toString();
                QC_name=map.get("QC_name").toString().replace("[","").replace("]","");
                jsonStr = JSONObject.fromObject(QC_name);
                QC_nameId=jsonStr.getString("id");
                content="你有"+project_name+QC_task_name+"编号为"+objectNumber+"的数据"+state+"!";
                fescoadQueryService.sendMessage(userMapper.getUserId(QC_nameId).getUserId(),url,content,project_name+QC_task_name);
            }
        }


    }

    /**
     * @Description : 自建任务下发通知，根据修改时间范围发送消息
     * @param ：
     * @author : Liun
     * @date : 2021/3/23
     */
    @Override
    public void  sendMessageToQCTask(){
        String url = "form/detail?schemaCode=task_down_send&sheetCode=task_down_send";
        Map<String,String> dateMap=getTimes(-2);
        String beginTime=dateMap.get("beginTime");
        String endTime=dateMap.get("endTime");
        List<Map> qcTaskIssueList=projectTaskIssueMapper.getQCTaskIssueList(beginTime,endTime);
        String QC_name;
        String task_name;
        String questionnaireCode;
        JSONObject jsonStr;
        String  QC_nameId;
        String content;
        if(qcTaskIssueList.size()>0){
            for(Map map:qcTaskIssueList){
                task_name=map.get("task_name").toString();
                questionnaireCode=map.get("questionnaireCode").toString();
                QC_name=map.get("QC_name").toString().replace("[","").replace("]","");
                jsonStr = JSONObject.fromObject(QC_name);
                QC_nameId=jsonStr.getString("id");
                content="你有"+task_name+questionnaireCode+"的任务，请处理!";
                fescoadQueryService.sendMessage(userMapper.getUserId(QC_nameId).getUserId(),url,content,task_name+questionnaireCode);
            }
        }
    }

    @Override
    public Map<String, Map<String, String>> getStoresList(String subjectName) {
        List<Map<String, String>> list = projectTaskIssueMapper.getStoresList(subjectName);
        Map<String, Map<String, String>> returnMap = new HashMap<>();
        for (Map<String, String> map : list) {
            String customerStoreNum = MapUtils.getString(map, "customerStoreNum");
            returnMap.put(customerStoreNum,map);
        }
        return returnMap;
    }
}
